#import "UPushPlugin.h"
//#if __has_include(<u_push_plugin/u_push_plugin-Swift.h>)
//#import <u_push_plugin/u_push_plugin-Swift.h>
//#else
//// Support project import fallback if the generated compatibility header
//// is not copied when this plugin is created as a library.
//// https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816
//#import "u_push_plugin-Swift.h"
//#endif

#import <UMCommon/UMCommon.h>
#import <UMPush/UMessage.h>
#import "MUPushManager.h"
#import <UIKit/UIKit.h>


typedef enum {
    TypeLogin = 101,
    TypeMessage = 102,
    TypeReceiver = 103
} TypeData;


@interface UPushPlugin()<FlutterStreamHandler>
@property(nonatomic,copy)NSString *deviceToken;
@property (nonatomic, strong) NSData *deviceTokenData;
@property(nonatomic,strong)FlutterMethodChannel *channel;

@property (nonatomic, strong) NSDictionary *cachePushMesDic;

@property (nonatomic, strong)FlutterEventChannel *eChannel;


@end


@implementation UPushPlugin{
    FlutterEventSink _eventSink;
}
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    //  [SwiftUPushPlugin registerWithRegistrar:registrar];
    
    UPushPlugin *p = [[UPushPlugin alloc]init];
    
    
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"u_push_plugin" binaryMessenger:[registrar messenger]];
    [registrar addApplicationDelegate:p];
    [registrar addMethodCallDelegate:p channel:channel];
    
    FlutterEventChannel *echannel = [FlutterEventChannel eventChannelWithName:@"u_push_plugin_e" binaryMessenger:[registrar messenger]];
    [echannel setStreamHandler:p];
}

- (void)sendDeviceTokenToUM {
    NSLog(@"将devicetoken传给友盟");
    [UMessage registerDeviceToken: self.deviceTokenData];
}

#pragma mark -- FlutterEventChannel代理

- (FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events {
    
    _eventSink = events;
    
    return nil;
}

- (FlutterError *)onCancelWithArguments:(id)arguments {
    
    _eventSink = nil;
    
    return nil;
}

-(void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    
    if([@"UMInitIOS" isEqualToString:call.method]){
        [MUPushManager UMInitWithMethodCall:call result:result];
        //初始化友盟完成之后再将deviceToken传给友盟
        [self sendDeviceTokenToUM];
    }else if([@"getCacheMessage" isEqualToString:call.method]){
        NSLog(@"就他妈离谱 getCacheMessage self.cachePushMesDic = %@", self.cachePushMesDic);
        if (self.cachePushMesDic) {
            NSDictionary *pushDic = [NSDictionary dictionaryWithDictionary:self.cachePushMesDic];
            self.cachePushMesDic = nil;
            result(@{@"data":pushDic, @"type":[NSNumber numberWithInt:102]});
        }
    }else if([@"addTags" isEqualToString:call.method]){
        if (call.arguments[@"tags"]) {
            [MUPushManager addTags:call.arguments[@"tags"] result:result];
        }
    }
    else if([@"deleteTags" isEqualToString:call.method]){
        if (call.arguments[@"tags"]) {
            [MUPushManager deleteTags:call.arguments[@"tags"] result:result];
        }
        
    }else if([@"getTags" isEqualToString:call.method]){
        [MUPushManager getTagsResult:result];
    }
    else if([@"addAlias" isEqualToString:call.method]){
        [MUPushManager addAlias:call.arguments[@"aliasId"] type:call.arguments[@"aliasType"] result:result];
    }else if([@"deleteAlias" isEqualToString:call.method]){
        [MUPushManager removeAlias:call.arguments[@"aliasId"] type:call.arguments[@"aliasType"] result:result];
    }
    else if([@"setAlias" isEqualToString:call.method]){
        [MUPushManager setAlias:call.arguments[@"aliasId"] type:call.arguments[@"aliasType"] result:result];
    }
    else if([@"getRegistrationId" isEqualToString:call.method]){
        
    }
    else if([@"UMSetBadgeClear" isEqualToString:call.method]){
        [MUPushManager setBadgeClear:[call.arguments[@"debgeClear"] boolValue]];
        
    }else if([@"getDeviceToken" isEqualToString:call.method]){
        result(self.deviceToken);
    }else {
        result(FlutterMethodNotImplemented);
    }
    
}


#pragma mark - AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    //程序杀死后 收到APNs推送 点击通知栏获取通知详细
    if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {
        
        // 当被杀死状态收到本地通知时执行的跳转代码
        NSDictionary *remoteCotificationDic = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        
        NSLog(@"离线消息推送点击通知栏");
        //  [self.channel invokeMethod:@"onReceiveOffLineNotification" arguments:remoteCotificationDic];
        
        //           UIViewController *vc = UIApplication.sharedApplication.keyWindow.rootViewController;
        //           UITextView *v = [[UITextView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
        //           [vc.view addSubview:v];
        //           v.text = [NSString stringWithFormat:@"%@",self.cachePushMesDic];
        
        self.cachePushMesDic  = remoteCotificationDic;
        
    }
    
    // Push组件基本功能配置
    UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
    //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
    entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionSound|UMessageAuthorizationOptionAlert;
    if (@available(iOS 10.0, *)) {
        [UNUserNotificationCenter currentNotificationCenter].delegate=self;
    } else {
        // Fallback on earlier versions
    }
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            NSLog(@"**********已经授权成功************");
        }else{
            NSLog(@"**********授权失败************");
        }
    }];
    
    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    // 方式1
    
    NSMutableString *deviceTokenString = [NSMutableString string];
    
    const char *bytes = deviceToken.bytes;
    
    int iCount = deviceToken.length;
    
    for (int i = 0; i < iCount; i++) {
        
        [deviceTokenString appendFormat:@"%02x", bytes[i]&0x000000FF];
    }
    NSLog(@"获取deviceToken：%@", deviceTokenString);
    
    //    [UMessage registerDeviceToken: deviceToken];
    
    self.deviceToken=deviceTokenString;
    self.deviceTokenData = deviceToken;
    
}


////iOS10新增：处理前台收到通知的代理方法
//-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
//    NSDictionary * userInfo = notification.request.content.userInfo;
//    if (@available(iOS 10.0, *)) {
//        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//            //应用处于前台时的远程推送接受
//            //关闭U-Push自带的弹出框
//            [UMessage setAutoAlert:NO];
//            //必须加这句代码
//            [UMessage didReceiveRemoteNotification:userInfo];
//
//            NSLog(@"应用处于前台时的远程推送接受：%@", userInfo);
//
//
//        }else{
//            //应用处于前台时的本地推送接受
//            NSLog(@"应用处于前台时的远程推送接受：%@", userInfo);
//        }
//    } else {
//        // Fallback on earlier versions
//    }
//
//
//    [self.channel invokeMethod:@"onReceiveNotification" arguments:userInfo];
//
//    //当应用处于前台时提示设置，需要哪个可以设置哪一个
//    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
//}

//#mark --------------iOS10以下通知处理-----------------

//iOS10以下使用这两个方法接收通知，
//-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
//{
//    [UMessage setAutoAlert:NO];
//    if([[[UIDevice currentDevice] systemVersion]intValue] < 10){
//        [UMessage didReceiveRemoteNotification:userInfo];
//        self.cachePushMesDic = userInfo;
//        [_channel invokeMethod:@"onReceiveNotification" arguments:userInfo];
//        completionHandler(UIBackgroundFetchResultNewData);
//    }
//}



//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        //关闭U-Push自带的弹出框
        [UMessage setAutoAlert:NO];
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
        NSLog(@"应用处于前台时的远程推送接受：%@", userInfo);
        
        
    }else{
        //应用处于前台时的本地推送接受
        NSLog(@"应用处于前台时的远程推送接受：%@", userInfo);
    }
    
    //    self.cachePushMesDic = userInfo;
    //
    if(_eventSink){
        NSDictionary *event = [UPushPlugin getresultDicFromDictionary:userInfo type:TypeReceiver];
        _eventSink(event);
    }
    //
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

// iOS 10 以下点击本地通知
//-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
//
//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    NSString *title = @"";
//    if (@available(iOS 8.2, *)) {
//        title = notification.alertTitle;
//    } else {
//        // Fallback on earlier versions
//    }
//
//    NSString *body = notification.alertBody;
//    NSString *action = notification.alertAction;
//
//    [dic setValue:title?:@"" forKey:@"title"];
//    [dic setValue:body?:@"" forKey:@"body"];
//    [dic setValue:action?:@"" forKey:@"action"];
//    NSLog(@"就他妈离谱 didReceiveLocalNotification");
//    self.cachePushMesDic = dic;
//
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self.channel invokeMethod:@"onNotificatiClickHandler" arguments:dic];
//    });
//}


//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    //    completionHandler();
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            //应用处于后台时的远程推送接受
            //必须加这句代码
            [UMessage didReceiveRemoteNotification:userInfo];
            NSLog(@"应用处于后台时的远程推送接受：%@", userInfo);
            
        }else{
            //应用处于后台时的本地推送接受
            NSLog(@"应用处于后台时的本地推送接受：%@", userInfo);
        }
    } else {
        // Fallback on earlier versions
    }
    
    
    UIApplicationState state = [UIApplication sharedApplication].applicationState;
    NSLog(@"应用处于后台时的本地推送接受：%ld", (long)state);
    
    //self.cachePushMesDic = userInfo;
    
    if (_eventSink){
        NSDictionary *event = [UPushPlugin getresultDicFromDictionary:userInfo type:TypeMessage];
        _eventSink(event);
        
        //在后台时点击push，使用103刷新页面
        if (state != UIApplicationStateActive) {
            NSDictionary *eventReceive = [UPushPlugin getresultDicFromDictionary:userInfo type:TypeReceiver];
            _eventSink(eventReceive);
        }
        
    }
    
    if(state == UIApplicationStateBackground){
        
        NSLog(@"app在后台点击通知栏");
        [self.channel invokeMethod:@"onReceiveOffLineNotification" arguments:userInfo];
    }else if (state == UIApplicationStateInactive){
        
        NSLog(@"冷启动点击通知栏");
        [self.channel invokeMethod:@"onNotificatiClickHandler" arguments:userInfo];
    }
}

+ (NSDictionary *)getresultDicFromDictionary:(NSDictionary *)dic type:(TypeData)type{
    
    NSDictionary *resultDic = @{};
    
    // NSError *error;
    // NSData *data = [NSData data];
    //if (dic) {
    //  data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    //}
    //NSString *jsonString = @"";
    //if (data) {
    //  jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    //}
    //[NSString stringWithFormat:@"%d",type]
    if (dic) {
        resultDic = @{@"data":dic, @"type":@(type)};
    }
    
    return resultDic;
}


@end
